//
//  ContentTableViewCell.m
//  SoundPill
//
//  Created by 温冬 on 15/6/9.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "ContentTableViewCell.h"
#import "plaza_viewModel.h"
#import "SDWebImageManager.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "recommedLabel.h"
#import "UIViewExt.h"
#import "DACircularProgressView.h"
#import "LoginViewController.h"

#define kleftGap  5
#define kupGap   8
#define kDeviceWidth [UIScreen mainScreen].bounds.size.width
#define kImageViewWidth [UIScreen mainScreen].bounds.size.width*0.07
#define kImageViewHeight 157
#define kLabelWidth [UIScreen mainScreen].bounds.size.width*0.18
#define kLabelHeight 20

@interface ContentTableViewCell ()
@property (strong, nonatomic) UIImageView *textMark;
@property (strong, nonatomic) UIImageView *imageMark;
@property (strong, nonatomic) UILabel *textMarkLabel;
@property (strong, nonatomic) UILabel *imageMarkLabel;
@property (strong, nonatomic) UIButton *avatarBtn;
@property (strong, nonatomic) DACircularProgressView *imageProgress;
@end

@implementation ContentTableViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        [self initSubViews];
    
        self.backgroundColor=[UIColor whiteColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    return self;
}


- (void)initSubViews
{
    
    
    // “图片
    _symbolImage = [[UIButton alloc] initWithFrame:CGRectZero];
    [self addSubview:_symbolImage];
    
    // 推荐理由
    _resonLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_resonLabel];
    
    // 作品图预览
    _worksImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_worksImage];
    
    
    // 半透明背景
    _background = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_background];
    
    // 图片
    _pesonHeadImage = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kImageViewWidth, kImageViewWidth)];
    image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kImageViewWidth, kImageViewWidth)];
    [_pesonHeadImage addSubview:image];
    [self addSubview:_pesonHeadImage];
   
    // 名字
    _personName = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_personName];
    
    self.avatarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:_avatarBtn];
    // 播放次数
    _playtimesBtn = [[plaza_button alloc] initWithFrame:CGRectZero];
    _playtimesBtn.backgroundColor = [UIColor clearColor];
    [self addSubview:_playtimesBtn];
    
    // 点按数量
    _heartCountBtn = [[plaza_button alloc]initWithFrame:CGRectZero];
    _heartCountBtn.backgroundColor = [UIColor clearColor];
    _heartCountBtn.enabled = YES;
    
    [self addSubview:_heartCountBtn];
    
    // 时长（分）
    _pointLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_pointLabel];
    [_pointLabel setTextColor:[UIColor whiteColor]];
    [_pointLabel setFont:[UIFont systemFontOfSize:45.0f]];
    
    // 时间-'
    _oneSymbol = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_oneSymbol];
    
    // 时长 (秒)
    _secondLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_secondLabel];
    [_secondLabel setTextColor:[UIColor whiteColor]];
    [_secondLabel setFont:[UIFont systemFontOfSize:45.0f]];
    
    // 时间-''
    _twoSymbol = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_twoSymbol];

    // 作品标题
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLabel.font = [UIFont systemFontOfSize:17.0f];
    _titleLabel.textColor = [UIColor whiteColor];
    [self addSubview:_titleLabel];
    
    // 播放图片
    _playImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_playImage];
    
    // 播放次数
    _playLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_playLabel];
    
    // 点赞图片
    _loveImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:_loveImage];
    
    // 点赞次数
    _loveLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_loveLabel];
    
    //分隔线
    self.imageProgress = [[DACircularProgressView alloc] initWithFrame:CGRectZero];
    _imageProgress.alpha = 1;
    _imageProgress.trackTintColor = [UIColor whiteColor];
    _imageProgress.progressTintColor = [UIColor blackColor];
    _imageProgress.roundedCorners = 0;
    [self addSubview:_imageProgress];
    
    self.textMark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Play_blackMark"]];
    _textMark.frame = CGRectZero;
    [self addSubview:_textMark];
    
    self.imageMark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Play_blueMark"]];
    _imageMark.frame = CGRectZero;
    [self addSubview:_imageMark];
    
    self.textMarkLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _textMarkLabel.text = @"字幕";
    _textMarkLabel.font = [UIFont systemFontOfSize:13];
    _textMarkLabel.textAlignment = NSTextAlignmentRight;
    _textMarkLabel.textColor = [UIColor whiteColor];
    [self addSubview:_textMarkLabel];
    
    self.imageMarkLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _imageMarkLabel.text = @"插图";
    _imageMarkLabel.font = [UIFont systemFontOfSize:13];
    _imageMarkLabel.textAlignment = NSTextAlignmentRight;
    _imageMarkLabel.textColor = [UIColor whiteColor];
    [self addSubview:_imageMarkLabel];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    // “图片
    
    if ([UIScreen mainScreen].bounds.size.height == 736) {
        _symbolImage.frame = CGRectMake(kleftGap * 3, 15, 20, 27);
    } else {
        _symbolImage.frame = CGRectMake(kleftGap * 3, 15, 20, 20);
    }
    [_symbolImage setImage:[UIImage imageNamed:@"quotes"] forState:UIControlStateNormal];
    // 调用计算label高度的方法
    if (![self.plazadataModel.reason isKindOfClass:[NSNull class]] && self.plazadataModel.reason.length > 0) {
        CGFloat labelHeight = [self heightForContentCell:self.plazadataModel.reason];
        _resonLabel.frame = CGRectMake(_symbolImage.frame.origin.x + _symbolImage.frame.size.width + 9,  18, self.contentView.frame.size.width - 59, labelHeight);
    } else {
        CGFloat labelHeight = [self heightForContentCell:@"暂无推荐理由"];
        _resonLabel.frame = CGRectMake(_symbolImage.frame.origin.x + _symbolImage.frame.size.width + 9,  18, self.contentView.frame.size.width - 59, labelHeight);
    }
    // 推荐理由
    _resonLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1.0];
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        _resonLabel.font = [UIFont systemFontOfSize:12.0f];
    } else if ([UIScreen mainScreen].bounds.size.height == 667) {
        _resonLabel.font = [UIFont systemFontOfSize:14];
    } else {
        _resonLabel.font = [UIFont systemFontOfSize:16];
    }
    _resonLabel.numberOfLines = 0;
    if (![self.plazadataModel.reason isKindOfClass:[NSNull class]]) {
        _resonLabel.text = [NSString stringWithFormat:@"%@",self.plazadataModel.reason];
    } else {
        _resonLabel.text = @"暂无推荐理由";
    }

    // 首图预览
    if ([UIScreen mainScreen].bounds.size.height == 667) {
        //6
        _worksImage.frame = CGRectMake(kleftGap * 3, _resonLabel.bottom + 17.5, kDeviceWidth - kleftGap * 6, 195);
    } else if ([UIScreen mainScreen].bounds.size.height == 736) {
        _worksImage.frame = CGRectMake(kleftGap * 3, _resonLabel.bottom + 17.5, kDeviceWidth - kleftGap * 6, 225);
    } else {
        _worksImage.frame = CGRectMake(kleftGap * 3, _resonLabel.bottom + 17.5, kDeviceWidth - kleftGap * 6, 150);
    }
    _imageProgress.frame = CGRectMake(_worksImage.frame.origin.x + _worksImage.frame.size.width / 2 - 20,_worksImage.frame.origin.y + _worksImage.frame.size.height / 2 - 20, 40, 40);

    [_worksImage setContentScaleFactor:[[UIScreen mainScreen] scale]];
    _worksImage.contentMode =  UIViewContentModeScaleAspectFill;
    _worksImage.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _worksImage.clipsToBounds  = YES;
    _worksImage.backgroundColor=[UIColor whiteColor];
    
    if (![self.plazadataModel.worksImageURL isEqual:[NSNull null]]) {
        __weak ContentTableViewCell *cell = self;
        [_worksImage setImageWithURL:[NSURL URLWithString:self.plazadataModel.worksImageURL] placeholderImage:[UIImage imageNamed:@"plazz_placeholderImage"]options:SDWebImageRetryFailed progress:^(NSUInteger receivedSize, long long expectedSize) {
            cell.imageProgress.hidden = NO;
                cell.imageProgress.progress = receivedSize / (float)expectedSize;
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                cell.imageProgress.hidden = YES;
//            });
        }];
    }
    
    // 半透明背景
//    _background.frame = CGRectMake(_worksImage.frame.origin.x, _worksImage.frame.origin.y, _worksImage.frame.size.width, _worksImage.frame.size.height);
    _background.frame = _worksImage.frame;
    _background.backgroundColor = [UIColor blackColor];
    _background.alpha = 0.33;
    
    
    // 时长（分）
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        _pointLabel.frame = CGRectMake(self.frame.size.width * 0.55 - 30, _worksImage.frame.origin.y + 25 ,28+30 , 38);
    } else if ([UIScreen mainScreen].bounds.size.height == 667) {
        _pointLabel.frame = CGRectMake(self.frame.size.width * 0.55 - 5, _worksImage.frame.origin.y + 25 ,28+30 , 38);
    } else if ([UIScreen mainScreen].bounds.size.height == 736) {
        _pointLabel.frame = CGRectMake(self.frame.size.width * 0.55 + 10, _worksImage.frame.origin.y + 25 ,28+30 , 38);
    }
    _pointLabel.textAlignment = NSTextAlignmentRight;
    if (![self.plazadataModel.duration isEqual:[NSNull null]]) {
        //文字
        NSString *recommendString = [NSString stringWithFormat:@"%@",self.plazadataModel.duration];
        //分
        int point =  recommendString.floatValue / 60;
        _pointLabel.text = [NSString stringWithFormat:@"%d", point];
    }
    
    // '
    _oneSymbol.frame = CGRectMake(_pointLabel.frame.origin.x + _pointLabel.frame.size.width, _pointLabel.frame.origin.y - 2, 12, 12);
    [_oneSymbol setImage:[UIImage imageNamed:@"minute"]];

    // 时长（秒）
    _secondLabel.frame = CGRectMake(_oneSymbol.frame.origin.x + _oneSymbol.frame.size.width + 3,_pointLabel.frame.origin.y, 60, 38);
    _secondLabel.textAlignment = NSTextAlignmentCenter;
    if (![self.plazadataModel.duration isEqual:[NSNull null]]) {
        //文字
        NSString *recommendString = [NSString stringWithFormat:@"%@",self.plazadataModel.duration];
        //秒
        int second = (int)recommendString.floatValue % 60;
        if (second < 10) {
            _secondLabel.text = [NSString stringWithFormat:@"0%d", second];
        }else{
            _secondLabel.text = [NSString stringWithFormat:@"%d", second];
        }
    }
    
    // "
    _twoSymbol.frame = CGRectMake(_secondLabel.frame.origin.x + _secondLabel.frame.size.width, _oneSymbol.frame.origin.y, 12, 12);
    [_twoSymbol setImage:[UIImage imageNamed:@"second"]];
    
    // 作品标题
    _titleLabel.frame = CGRectMake(50,  _pointLabel.frame.origin.y + _pointLabel.frame.size.height + 10, self.contentView.frame.size.width - 100, 44);
    [_titleLabel setFont:[UIFont systemFontOfSize: 18.0f]];
    _titleLabel.numberOfLines = 0;
    _titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    _titleLabel.textAlignment = NSTextAlignmentRight;
    _titleLabel.adjustsFontSizeToFitWidth = YES;
    //_titleLabel.backgroundColor = [UIColor cyanColor];
    
    if (![self.plazadataModel.title isEqual:[NSNull null]]) {
        //文字
        NSString *recommendString = [NSString stringWithFormat:@"%@\n",self.plazadataModel.title];
        _titleLabel.text = recommendString;
    }
    
    //用户头像
    _pesonHeadImage.frame = CGRectMake(_worksImage.left, _worksImage.bottom + 5, 18, 18);
    _pesonHeadImage.backgroundColor=[UIColor whiteColor];
    
    if (![self.plazadataModel.headImageURL isEqual:[NSNull null]]) {
        [image setImageWithURL:[NSURL URLWithString:self.plazadataModel.headImageURL] placeholderImage:[UIImage imageNamed:@"default_head.png"]];
    }
    [_pesonHeadImage setBackgroundImage:image.image forState:UIControlStateNormal];
    
    //名字
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        _personName.frame = CGRectMake(_pesonHeadImage.right + 15, _pesonHeadImage.top + 2 ,self.contentView.width*0.4, 20);
        _personName.font = [UIFont boldSystemFontOfSize:12];
    } else if ([UIScreen mainScreen].bounds.size.height == 667) {
        _personName.frame = CGRectMake(_pesonHeadImage.right + 15, _pesonHeadImage.top + 4,self.contentView.width*0.4, 20);
        _personName.font = [UIFont boldSystemFontOfSize:14];
    } else {
        _personName.frame = CGRectMake(_pesonHeadImage.right + 15, _pesonHeadImage.top + 6,self.contentView.width*0.4, 20);
        _personName.font = [UIFont boldSystemFontOfSize:14];
    }

    _personName.textColor = [UIColor blackColor];
    
//    _personName.backgroundColor = [UIColor redColor];
    if (![self.plazadataModel.personName isEqual:[NSNull null]]) {
        _personName.text = [NSString stringWithFormat:@"%@",self.plazadataModel.personName];
    }
    _avatarBtn.frame = CGRectMake(_pesonHeadImage.frame.origin.x, _pesonHeadImage.frame.origin.y - 10, _pesonHeadImage.frame.size.width + _personName.frame.size.width, _personName.frame.size.height + 20);
    _avatarBtn.backgroundColor = [UIColor clearColor];
    [_avatarBtn addTarget:self action:@selector(pushUserMessage) forControlEvents:UIControlEventTouchUpInside];
    // 点赞次数
//    _loveLabel.frame = CGRectMake(self.frame.size.width - 15 - 30, _personName.origin.y, 30, 20);
    _loveLabel.font = [UIFont systemFontOfSize:13.0f];
    _loveLabel.textColor = [UIColor blackColor];
    _loveLabel.textAlignment = NSTextAlignmentCenter;
    if (![self.plazadataModel.playTimes isEqual:[NSNull null]]) {
        _loveLabel.text = [NSString stringWithFormat:@"%@",self.self.plazadataModel.heartCount];
       CGSize size = [self boundingRectWithSize:CGSizeMake(30, 20) text:_loveLabel.text font:_loveLabel.font];
        _loveLabel.frame = CGRectMake(self.frame.size.width - 15 - size.width, _personName.origin.y, size.width, 22);
    }
    // 点赞图片
    _loveImage.frame = CGRectMake(_loveLabel.frame.origin.x - 20, _personName.origin.y, 22, 22);
    _loveImage.image = [UIImage imageNamed:@"loveicon"];
    
    // 播放次数
//    _playLabel.frame = CGRectMake(_loveImage.frame.origin.x - 30 - 5, _personName.origin.y, 30, 20);
    _playLabel.textAlignment = NSTextAlignmentCenter;
    _playLabel.font = [UIFont systemFontOfSize:13.0f];
    _playLabel.textColor = [UIColor blackColor];
    if (![self.plazadataModel.playTimes isEqual:[NSNull null]]) {
        _playLabel.text = [NSString stringWithFormat:@"%@",self.plazadataModel.playTimes];
         CGSize playSize = [self boundingRectWithSize:CGSizeMake(30, 20) text:_playLabel.text font:_playLabel.font];
        _playLabel.frame = CGRectMake(_loveImage.left - playSize.width - 10, _personName.origin.y, playSize.width, 22);
    }
    // 播放图片
    _playImage.frame = CGRectMake(_playLabel.frame.origin.x - 20, _personName.origin.y, 22, 22);
    _playImage.image = [UIImage imageNamed:@"playicon"];
    //标签
    self.tagView.frame = CGRectMake(1 , _playImage.frame.size.height + _playImage.frame.origin.y,[UIScreen mainScreen].bounds.size.width,10);

    
    if (_plazadataModel.blue.boolValue == YES) {
        _imageMark.frame = CGRectMake(_twoSymbol.right - 45, _worksImage.bottom - 30, 15, 15);
        _imageMarkLabel.frame = CGRectMake(_imageMark.right, _imageMark.top, 30, 20);
        _imageMarkLabel.center = CGPointMake(_imageMark.center.x + 20, _imageMark.center.y);
        _imageMarkLabel.hidden = NO;
        _imageMark.hidden = NO;
        [self addAnimation:_imageMark repeate:MAXFLOAT];
    } else {
        _imageMark.hidden = YES;
        _imageMarkLabel.hidden = YES;
        [_imageMark.layer removeAllAnimations];
    }
    
    if (_plazadataModel.black.boolValue == YES) {
        _textMark.hidden = NO;
        _textMarkLabel.hidden = NO;
        if (_imageMark.hidden == YES) {
            _textMark.frame = CGRectMake(_twoSymbol.right - 45, _worksImage.bottom - 30, 15, 15);
        } else {
            _textMark.frame = CGRectMake(_imageMark.left, _imageMark.top - 20, 15, 15);
        }
        _textMarkLabel.frame = CGRectMake(_textMark.right, _imageMark.top, 30, 20);
        _textMarkLabel.center = CGPointMake(_textMark.center.x + 20, _textMark.center.y);
        [self addAnimation:_textMark repeate:MAXFLOAT];
    } else {
        _textMark.hidden = YES;
        _textMarkLabel.hidden = YES;
        [_textMark.layer removeAllAnimations];
    }

}
- (void)addAnimation:(UIImageView *)mask repeate:(CGFloat)repeate
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    // 动画选项设定
    animation.duration = 0.5; // 动画持续时间
    animation.repeatCount = repeate; // 重复次数
    animation.autoreverses = YES; // 动画结束时执行逆动画
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    // 缩放倍数
    animation.fromValue = [NSNumber numberWithFloat:1.0]; // 开始时的倍率
    animation.toValue = [NSNumber numberWithFloat:1.25]; // 结束时的倍率
    // 添加动画
    [mask.layer addAnimation:animation forKey:@"scale-layer"];
}
- (void)pushUserMessage
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToUser" object:_plazadataModel.UserID];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (CGSize)boundingRectWithSize:(CGSize)size text:(NSString *)text font:(UIFont *)font
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    CGSize retSize = [text boundingRectWithSize:size
                                        options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                     attributes:attribute
                                        context:nil].size;
    
    return retSize;
}

#pragma mark cell自适应高度
- (CGFloat)heightForContentCell:(NSString *)text{
    
    //1.设置内容显示最大高度 其中宽度跟contentsLabel高度一样,高度尽量设置大一些
    CGSize size = CGSizeMake(kDeviceWidth - 59, 40);
    
    //2.NSStringDrawingUsesLineFragmentOrigin 按行计算内容高度
    
    //3.创建存放字体大小的字典,字体大小要与contentsLabel字体大小一样
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:12.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    } else if ([UIScreen mainScreen].bounds.size.height == 667) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    } else {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:16.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    }
}
@end
